package com.example.demo.service.impl;

import com.example.demo.entity.Folder;
import com.example.demo.entity.User;
import com.example.demo.exception.BusyException;
import com.example.demo.exception.login.WrongPasswordException;
import com.example.demo.exception.modify.UserNotExitException;
import com.example.demo.exception.regist.UserExitException;
import com.example.demo.exception.regist.UserNullException;
import com.example.demo.mapper.FolderMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.Bcrypt;
import com.example.demo.utils.FolderUtils;
import com.example.demo.utils.Url2Base64;
import com.jcraft.jsch.SftpException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    FolderMapper folderMapper;
    private FolderUtils folderUtils=new FolderUtils();
    private Url2Base64 url2Base64=new Url2Base64();
    @Override
    public void login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(username, password));
    }

    @Override
    public void modify(User user, MultipartFile file) throws Exception {//修改个人信息
        //获取用户名
        Subject subject=SecurityUtils.getSubject();
        User user1 =(User) subject.getPrincipal();
        String username=user1.getUsername();
        User exitUser=userMapper.selectALL(username);//判断用户是否存在
        int res=0;
        if(exitUser==null){
            throw new UserNotExitException();
        }else {
            user.setUsername(username);
            if(file!=null) {
                String basePath = FolderUtils.basePath + "/" + username;
                String filename = file.getOriginalFilename();
                folderUtils.uploadFile(basePath, FolderUtils.header, filename, file);
                user.setPicture("http://47.98.175.236:8088/" + username + "/" + FolderUtils.header + "/" + filename);
            }else{
                user.setPicture(exitUser.getPicture());
            }
            if(user.getNickname()==null){
                user.setNickname(exitUser.getNickname());
            }//判断昵称是否为空
            if(user.getSex()==null){
                user.setSex(exitUser.getSex());
            }
            if(user.getCity()==null){
                user.setCity(exitUser.getCity());
            }
            if(user.getProvince()==null){
                user.setProvince(exitUser.getProvince());
            }
            if(user.getIntroduction()==null){
                user.setIntroduction(exitUser.getIntroduction());
            }
//            if(user.getPicture()==null){
//                user.setPicture(exitUser.getPicture());
//            }
            res=userMapper.updateModify(user);//修改该用户信息
            if(res<=0){
                throw new BusyException();
            }
        }
    }
    @Override
    public User getinfo(){//获取个人信息
        //获取用户名
        Subject subject=SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        String username=user.getUsername();
        User exitUser=userMapper.selectALL(username);
        return exitUser;
    }

    @Override
    public Integer[] notesNumber(){
        Integer notesNum=0,daysNum=0,collectNum=0;
        //获取用户名
        Subject subject=SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        String username=user.getUsername();
        Date date=user.getDate();//注册时间

        Date nowdate=new Date();
        //SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date nowdate=sdf.format(now);//截取的系统当前时间
        long diff= nowdate.getTime()-date.getTime();
        long days= diff/(1000*60*60*24);
        daysNum=new Integer((int) days);
        notesNum=userMapper.selectNotesNum(username);//该用户的笔记数


        Integer Num[]={daysNum,notesNum,collectNum};//获取用户使用天数，笔记数，收藏数。
        return Num;
    }

    //修改密码
    @Override
    public void changePwd(String currentPwd, String newPwd) {
        int res=0;
        Subject subject=SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        String username=user.getUsername();
        User user1=userMapper.selectPwd(username);
        String password=user1.getPassword();
        user1.setUsername(username);
        if(user1!=null) {
            if(!Bcrypt.decodeByBcrypt(currentPwd,password)){
                throw new WrongPasswordException();
            } else{
                user1.setPassword(Bcrypt.encodeByBcrypt(newPwd));
                res=userMapper.updateUser(user1);
                if(res<=0) {
                    throw new BusyException();
                }
            }
        }else{
            throw new UserNotExitException();
        }
    }

    @Override
    public String url2Base64(String url) throws IOException {
        String Base64;
        Subject subject=SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        String username=user.getUsername();
        Base64=url2Base64.urlToBase64(url,username);
        if(Base64.equals("越权")){
            throw new BusyException();
        }
        return Base64;
    }


    @Override
    public void register(User user) throws IOException, SftpException {
        if(user.getUsername().equals("") || user.getPassword().equals("")){
            throw new UserNullException();
        }
        User exitUser=userMapper.selectByUsername(user.getUsername());
        int res=0;
        if(exitUser!=null){
            throw new UserExitException();
        }else{
            //用户注册即为他在远程服务器上创建一个自己的文件夹
            folderUtils.createFolder(FolderUtils.basePath,user.getUsername());
            //为该用户创建一个存储文件的文件夹,名为"我的文件夹";创建一个存储头像的文件夹，名为“头像目录”;创建一个储存回收站文件的文件夹，名为“回收站”;创建一个存储图片的目录（主要做预览）
            String base1= FolderUtils.basePath +"/"+user.getUsername();
            folderUtils.createFolder(base1, FolderUtils.file);
            folderUtils.createFolder(base1, FolderUtils.header);
            folderUtils.createFolder(base1, FolderUtils.trash);
            folderUtils.createFolder(base1,FolderUtils.picture);
            //向数据库中插入用户的记录
            String pwd= Bcrypt.encodeByBcrypt(user.getPassword());
            user.setPassword(pwd);
            res=userMapper.insertUser(user);
            if(res<=0) {
                throw new BusyException();
            }
            //在数据库中插入相应的默认文件夹,path为主键
            for(int i=0;i<4;i++){
                Folder fd=new Folder();
                fd.setUsername(user.getUsername());
                if(i==0){
                    fd.setPath(user.getUsername()+"/"+FolderUtils.file);
                }else if(i==1){
                    fd.setPath(user.getUsername()+"/"+FolderUtils.header);
                }else if(i==2){
                    fd.setPath(user.getUsername()+"/"+FolderUtils.trash);
                    //回收站的文件夹默认为被删除
                    fd.setBeDeleted(true);
                }else{
                    fd.setPath(user.getUsername()+"/"+FolderUtils.picture);
                }
                folderMapper.insertFolder(fd);
            }

        }


    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }



}
